package cn.service;

import cn.constant.Messages;
import cn.entity.Article;
import cn.entity.User;
import cn.repository.ArticleRepository;
import cn.util.AuthUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.PageRequest;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;
import java.util.UUID;

/**
 * @author m on 2023/1/28
 * Description:
 */
@Service
public class ArticleServiceImpl implements ArticleService{

    private  final ArticleRepository articleRepository;

    @Autowired
    public ArticleServiceImpl(ArticleRepository articleRepository) {
        this.articleRepository = articleRepository;
    }

    @Override
    public Article getById(UUID id) {
        return articleRepository.findById(id).orElse(null);
    }

    @Override
    public Article createArticle(Article article) {
        return articleRepository.save(article);
    }

    @Override
    public Article updateArticle(Article article,String token) {
        if(AuthUtils.invalid(article.getUser().getId(),token)){
            return null;
        }
        article.setUpdateTime(new Date());
        articleRepository.save(article);
        return article;
    }

    @Override
    public Messages deleteArticle(UUID id,String token) {
        Article article = articleRepository.findById(id).orElse(null);
        Messages msg;
        if (article == null) {
            return Messages.WRONG_ID;
        }
        UUID userId = AuthUtils.getUser(token).getId();
        Integer type = AuthUtils.getUser(token).getType();

        if(article.getUser().getId() == userId){
            return Messages.NO_PERMISSION;
        }
        if (type != User.TYPE_ADMIN) {
            return Messages.NO_PERMISSION;
        }
        articleRepository.delete(article);
        return Messages.SUCCESS;
    }

    @Override
    public List<Article> getArticlesByUser(User user) {
        return articleRepository.findArticlesByUser(user);
    }

    @Override
    public List<Article> get(int page, int size) {
        return articleRepository.findAllByOrderByCreateTimeDesc(PageRequest.of(page,size));
    }

    @Override
    public List<Article> search(String kw) {
        return articleRepository.findByQuery(kw);
    }
}
